<template>
  <Dialog :visible="visible" width="70%" :title="visibleTitle" @close="visibleClose"
          :footer="false">
    <el-form label-width="80px">
      <el-row :gutter="24">
        <el-col :span="19">
          <el-col :span="10" :xs="24">
            <el-form-item :label="$t('可登录IP')">
              <el-input v-model="page.ip" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="10" :xs="24">
            <el-form-item :label="$t('状态')">
              <el-select
                  style="width: 100%"
                  v-model="page.status"
                  clearable
              >
                <el-option :label="$t('启用')" :value="1"></el-option>
                <el-option :label="$t('禁用')" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="5" :xs="24" style="text-align: right">
          <el-button type="primary" @click="getTableData">{{ $t('查询') }}</el-button>
          <el-button @click="resetSearch">{{ $t('重置') }}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align: right;margin-bottom: 15px">
      <!--      <el-button type="primary" @click="allStatusChange">{{ $t('全部禁/启用') }}</el-button>-->
      <el-button type="primary" v-show="$permiss[1029]" @click="addIPVisible">{{ $t('新增') }}</el-button>
    </div>
    <Table :table-data="tableData" :table-column="tableColumn" :page="page" @handleSizeChange="handleSizeChange"
           @handleCurrentChange="handleCurrentChange">
      <template slot="status" slot-scope="{row}">
        <el-switch :disabled="!$permiss[1030]" @change="changeStatus(row)" :value="row.status === 1"></el-switch>
      </template>
      <template slot="loginDay" slot-scope="{row}">
        <el-tag v-for="item in row.loginDayList" style="margin: 0 5px 5px 0" :disable-transitions="true" :key="item">
          {{ setWeeks(item) }}
        </el-tag>
      </template>
      <template slot="time" slot-scope="{row}">
        {{ row.loginStartTime }} <span v-show="row.loginStartTime || row.loginStartTime">-</span> {{ row.loginEndTime }}
      </template>
      <template slot="handle" slot-scope="{row}">
        <el-button type="text" v-show="$permiss[1029]" @click="editIPVisible(row)">{{ $t('编辑') }}</el-button>
      </template>
    </Table>
    <!--    IP增改-->
    <Dialog append-body :visible.sync="IPVisible.isShow" :title="IPVisible.title" width="45%"
            @cancel="IPVisible.isShow = false"
            @close="clearForm" @confirm="IPConfirm">
      <el-form label-width="100px" ref="form" :model="form" :rules="rulesForm">
        <el-row :gutter="24" style="margin: 0">
          <el-form-item prop="ip" :label="$t('可登录IP')">
            <el-input v-model="form.ip" oninput="value = value.replace(/[^\d.]/g, '')"/>
          </el-form-item>
          <el-form-item :label="$t('可登录时间')" prop="loginStartTime">
            <el-col :span="11">
              <el-time-select
                  v-if="loginTimeShow"
                  style="width: 100%;"
                  :placeholder="$t('起始时间')"
                  v-model="form.loginStartTime"
                  :picker-options="{
                      start: '00:00',
                      end: '23:59',
                      maxTime:form.loginEndTime
                  }"
              >
              </el-time-select>
            </el-col>
            <el-col :span="1" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-time-select
                  v-if="loginTimeShow"
                  ref="loginEndTime"
                  style="width: 100%;"
                  :placeholder="$t('结束时间')"
                  v-model="form.loginEndTime"
                  :picker-options="{
                     start: '00:00',
                      end: '23:59',
                     minTime: form.loginStartTime
                  }">
              </el-time-select>
            </el-col>
          </el-form-item>
          <el-form-item :label="$t('可登录星期')" prop="loginDayCheck">
            <el-checkbox :indeterminate="isIndeterminate" v-model="loginDayCheckAll" @change="loginDayCheckAllChange">
              {{ $t('全选') }}
            </el-checkbox>
            <el-checkbox-group v-model="form.loginDayCheck" @change="loginDayCheckChange">
              <el-checkbox :label="1">{{ $t('星期一') }}</el-checkbox>
              <el-checkbox :label="2">{{ $t('星期二') }}</el-checkbox>
              <el-checkbox :label="3">{{ $t('星期三') }}</el-checkbox>
              <el-checkbox :label="4">{{ $t('星期四') }}</el-checkbox>
              <el-checkbox :label="5">{{ $t('星期五') }}</el-checkbox>
              <el-checkbox :label="6">{{ $t('星期六') }}</el-checkbox>
              <el-checkbox :label="7">{{ $t('星期日') }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :label="$t('备注')">
            <el-input type="textarea" :rows="5" v-model="form.remarks"/>
          </el-form-item>
        </el-row>
      </el-form>
    </Dialog>
  </Dialog>
</template>

<script>
import {addNetwork,fetchNetwork,updateNetwork,updateNetworkStatus} from '@/api/system'
export default {
  name: "loginPlace",
  props: {
    rows: Object,
    visible: Boolean
  },
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableColumn: [
        {label: this.$t('可登录IP'), prop: 'ip', align: 'center', minWidth: 150},
        {label: this.$t('可登录时间'), slot: 'time', align: 'center', minWidth: 150},
        {label: this.$t('可登录星期'), slot: 'loginDay', align: 'center', minWidth: 200},
        {label: this.$t('创建人'), prop: 'createUserName', align: 'center'},
        {label: this.$t('创建时间'), prop: 'createTime', align: 'center', minWidth: 150},
        {label: this.$t('修改人'), prop: 'updateUserName', align: 'center'},
        {label: this.$t('修改时间'), prop: 'updateTime', align: 'center', minWidth: 150},
        {label: this.$t('备注'), prop: 'remarks', align: 'center'},
        {label: this.$t('状态'), prop: 'status', slot: 'status', align: 'center'},
        {label: this.$t('操作'), slot: 'handle', align: 'center', isHide: !this.$permiss[1028]},
      ],
      tableData: [],
      loginTimeShow: false,
      IPVisible: {
        isShow: false,
        type: '',
        title: ''
      },
      form: {
        loginDayCheck: [1, 2, 3, 4, 5, 6, 7],
      },
      isIndeterminate: true,
      loginDayCheckAll: false,
      rulesForm: {
        ip: [
          {required: true, message: this.$t('不能为空')}
        ],
        loginStartTime: [
          {
            required: false, type: 'date', validator: (rule, value, callback) => {
              const {loginStartTime, loginEndTime} = this.form
              if (loginStartTime && !loginEndTime) {
                return callback(new Error(this.$t('请填写结束时间')))
              } else if (!loginStartTime && loginEndTime) {
                return callback(new Error(this.$t('请填写起始时间')))
              }
              return callback()
            },
            trigger: 'change'
          }],
        loginDayCheck: [
          {
            type: 'array', required: true, message: this.$t('不能为空')
          }
        ]
      }
    }
  },
  computed: {
    visibleTitle() {
      return this.rows.name + ' - ' + this.$t('登录IP限制')
    }
  },
  watch: {
    visible(value) {
      if (value) {
        this.getTableData()
      }
    }
  },
  methods: {
    async getTableData() {
      const params = {
        roleId: this.rows.id
      }
      for (let key in this.page) {
        if (this.page[key] || this.page[key] === 0) {
          params[key] = this.page[key]
        }
      }
      const res = await fetchNetwork(params)
      if (res.code === 1) {
        const {list, pageNum, pageSize, total} = res.data
        this.tableData = list.map(item => {
          if (item.loginDay) {
            item.loginDayList = item.loginDay.split(',').sort((a, b) => a - b)
          }
          return item
        })
        this.page = {
          ...this.page,
          pageNum, pageSize, total
        }
      }
    },
    resetSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    async changeStatus({id}) {
      const formData = new FormData()
      formData.append('id', id)
      const res = await updateNetworkStatus(formData)
      if (res.code === 1) {
        this.$message.success(this.$t('操作成功'))
        this.getTableData()
      }
    },
    //  复选全选
    loginDayCheckAllChange(val) {
      this.form.loginDayCheck = val ? [1, 2, 3, 4, 5, 6, 7] : [];
      this.isIndeterminate = false;
    },
    //复选选中
    loginDayCheckChange(value) {
      let checkedCount = value.length;
      this.loginDayCheckAll = checkedCount === 7
      this.isIndeterminate = checkedCount > 0 && checkedCount < 7;
    },
    addIPVisible() {
      this.IPVisible = {
        isShow: true,
        type: 'add',
        title: this.$t('新增')
      }
      this.loginTimeShow = true
      this.loginDayCheckAll = true;
      this.isIndeterminate = false;
      this.form.loginDayCheck = [1, 2, 3, 4, 5, 6, 7]
    },
    editIPVisible(row) {
      const {id, loginEndTime, loginStartTime, remarks, ip} = row
      this.IPVisible = {
        isShow: true,
        type: 'edit',
        title: this.$t('编辑')
      }
      let loginDayCheck = []
      if (row.loginDay) {
        loginDayCheck = row.loginDay.split(',').map(item => parseInt(item))
      }
      if (loginDayCheck.length === 7) {
        this.loginDayCheckAll = true;
        this.isIndeterminate = false;
      } else {
        this.loginDayCheckAll = false;
        this.isIndeterminate = true;
      }
      this.form = {
        ip,
        loginDayCheck,
        id,
        remarks,
        loginEndTime,
        loginStartTime,
      }
      // time-select 第二次回显值问题
      this.loginTimeShow = true
    },
    IPConfirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          let loginDay = ''
          const type = this.IPVisible.type
          const api = (params) => type === 'add' ? addNetwork(params) : updateNetwork(params)
          const message = type === 'add' ? this.$t('新增成功') : this.$t('编辑成功')
          this.form.loginDayCheck.sort((a, b) => a - b).forEach((item, index) => {
            let str = ''
            this.form.loginDayCheck.length === (index + 1) ? str = '' : str = ','
            loginDay += item + str
          })
          const params = {
            loginDay,
            ...this.form,
            roleId: this.rows.id,
            loginEndTime: this.form.loginEndTime || '',
            loginStartTime: this.form.loginStartTime || '',
            loginDayCheck: undefined
          }
          const res = await api(params)
          if (res.code === 1) {
            this.IPVisible.isShow = false
            this.$message.success(message)
            this.getTableData()
          }
        }
      })
    },
    clearForm() {
      this.loginTimeShow = false
      this.form = {
        loginDayCheck: []
      }
      this.$refs.form.resetFields()
    },
    visibleClose() {
      this.$emit('update:visible', false)
    },
    setWeeks(val) {
      let value = ''
      switch (val) {
        case '1' :
          value = this.$t('星期一')
          break;
        case '2' :
          value = this.$t('星期二')
          break;
        case '3' :
          value = this.$t('星期三')
          break;
        case '4' :
          value = this.$t('星期四')
          break;
        case '5' :
          value = this.$t('星期五')
          break;
        case '6' :
          value = this.$t('星期六')
          break;
        case '7' :
          value = this.$t('星期日')
      }
      return value
    }
  },
  beforeDestroy() {
    this.$emit('update:visible', false)
  }
}
</script>

<style scoped>

</style>
